﻿using System.ComponentModel.DataAnnotations;
using System.Net;

namespace Blazor.Validators;

public class GuidAttribute: ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value is null || string.IsNullOrWhiteSpace(value.ToString()))
        {
            ErrorMessage = ValidatorLocalization.BlankString;
            return new ValidationResult(ValidatorLocalization.BlankString);
        }

        var guidString = value.ToString();
        if (Guid.TryParse(guidString, out _))
        {
            return ValidationResult.Success;
        }

        ErrorMessage = ValidatorLocalization.InvalidGuid;
        return new ValidationResult(ValidatorLocalization.InvalidGuid);
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name);
    }
}